package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 付
 */
@Slf4j
@Configuration
@EnableFeignClients(basePackages = "com.leyou.auth.client")
@EnableConfigurationProperties(ClientProperties.class)
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
public class AuthConfiguration {

    @Autowired
    private AuthClient authClient;

    @Bean
    public JwtUtils jwtUtils(ClientProperties prop) throws InterruptedException {
        while (true) {
            try {
                // 申请秘钥
                String key = authClient.getSecretKey(prop.getClientId(), prop.getSecret());
                log.info("获取秘钥成功！");
                // 初始化JwtUtils工具
                return new JwtUtils(key);
            } catch (Exception e) {
                log.error("申请jwt秘钥失败，原因：{}, 会在10秒后重试",e.getMessage());
                Thread.sleep(10000);
            }
        }
    }
}
